package com.example.javaow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javaow.domain.base.ResponseResult;
import com.example.javaow.domain.dto.DeviceDto;
import com.example.javaow.domain.entity.Device;
import com.example.javaow.domain.entity.DeviceGroup;
import com.example.javaow.domain.vo.DeviceVo;
import com.example.javaow.mapper.DeviceGroupMapper;
import com.example.javaow.mapper.DeviceMapper;
import com.example.javaow.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

// DeviceServiceImpl.java
@Service
@Slf4j
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceGroupMapper deviceGroupMapper;
    @Override
    public ResponseResult add(DeviceDto deviceDto) {
        log.info("添加设备：{}", deviceDto);
        Device device = new Device();
        String deviceAddress = deviceDto.getDeviceAddress();
        //只能输入1-255的数字
        if(deviceAddress != null && !deviceAddress.matches("^(?:[1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])$")) {
            return ResponseResult.error("设备地址必须是1-255之间的数字");
        }
        //查询地址是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceAddress, deviceAddress);
        if(deviceMapper.selectOne(queryWrapper) != null)
        BeanUtils.copyProperties(deviceDto, device);
        device.setCreatetime(LocalDateTime.now());
        int result = deviceMapper.insert(device);
        if(result <= 0)
            return ResponseResult.error("添加设备失败");
        return ResponseResult.success("添加设备成功");
    }

    @Override
    public ResponseResult update(DeviceDto deviceDto) {
        log.info("更新设备：{}", deviceDto);
        //只能输入1-255的数字
        String deviceAddress = deviceDto.getDeviceAddress();
        if(deviceAddress != null && !deviceAddress.matches("^(?:[1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])$")) {
            return ResponseResult.error("设备地址必须是1-255之间的数字");
        }
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto, device);
        device.setUpdatetime(LocalDateTime.now());
        int result = deviceMapper.updateById(device);
        if(result <= 0)
            return ResponseResult.error("更新设备失败");
        return ResponseResult.success("更新设备成功");
    }

    @Override
    public ResponseResult delete(Long[] ids) {
        log.info("删除设备：{}", ids);
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Device::getId, ids);
        int result = deviceMapper.delete(queryWrapper);
        if(result <= 0)
            return ResponseResult.error("删除设备失败");
        return ResponseResult.success("删除设备成功");
    }

    @Override
    public ResponseResult getById(Long id) {
        log.info("查询设备：{}", id);
        Device device = deviceMapper.selectById(id);
        DeviceVo deviceVo = new DeviceVo();
        BeanUtils.copyProperties(device, deviceVo);
        LambdaQueryWrapper<DeviceGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceGroup::getId, device.getGroupId());
        DeviceGroup deviceGroup = deviceGroupMapper.selectOne(queryWrapper);
        deviceVo.setGroupName(deviceGroup.getName());
        return ResponseResult.success(deviceVo);
    }

    @Override
    public IPage<DeviceVo> getByConditions(
            int pageNum, int pageSize,
            String deviceAddress, String deviceNumber, String deviceName,
            String deviceType, Long groupId, String status, String location,
            String keyword) {

        // 创建分页对象
        IPage<Device> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();

        // 1. 全局 keyword 模糊匹配
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.and(i -> {
                i.like(Device::getDeviceAddress, keyword.trim())
                        .or().like(Device::getDeviceNumber, keyword.trim())
                        .or().like(Device::getDeviceName, keyword.trim())
                        .or().like(Device::getModel, keyword.trim())
                        .or().like(Device::getLocation, keyword.trim());
            });
        }

        // 2. 设备地址（模糊）
        if (deviceAddress != null && !deviceAddress.isEmpty()) {
            wrapper.like(Device::getDeviceAddress, deviceAddress);
        }

        // 3. 设备编号（模糊）
        if (deviceNumber != null && !deviceNumber.isEmpty()) {
            wrapper.like(Device::getDeviceNumber, deviceNumber);
        }

        // 4. 设备名称（模糊）
        if (deviceName != null && !deviceName.isEmpty()) {
            wrapper.like(Device::getDeviceName, deviceName);
        }

        // 5. 设备类型（精确）
        if (deviceType != null && !deviceType.isEmpty()) {
            wrapper.eq(Device::getDeviceType, deviceType);
        }

        // 6. 所属分组（精确）
        if (groupId != null) {
            wrapper.eq(Device::getGroupId, groupId);
        }

        // 7. 状态（支持逗号分隔）
        if (status != null && !status.isEmpty()) {
            if (status.contains(",")) {
                String[] statusArray = status.split(",");
                wrapper.in(Device::getStatus, statusArray);
            } else {
                wrapper.eq(Device::getStatus, status);
            }
        }

        // 8. 安装位置（模糊）
        if (location != null && !location.isEmpty()) {
            wrapper.like(Device::getLocation, location);
        }

        // 按创建时间降序排列
        wrapper.orderByDesc(Device::getCreatetime);

        // 执行查询
        IPage<Device> resultPage = deviceMapper.selectPage(page, wrapper);

        // 转换为 VO（并填充 groupName）
        IPage<DeviceVo> voPage = resultPage.convert(device -> {
            DeviceVo vo = new DeviceVo();
            BeanUtils.copyProperties(device, vo);

            // 查询并设置 groupName
            if (device.getGroupId() != null) {
                DeviceGroup deviceGroup = deviceGroupMapper.selectById(device.getGroupId());
                String groupName = deviceGroup != null ? deviceGroup.getName() : null;
                vo.setGroupName(groupName != null ? groupName : "未命名分组");
            }

            return vo;
        });

        return voPage;
    }
}